﻿using B.MESUI.Login.EquipmentManagement.DTO;
using B.MESUI.Login.EquipmentManagement.Model;
using DevExpress.ClipboardSource.SpreadsheetML;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using Standard;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace B.MESUI.Login.EquipmentManagement.DeviceLedgerService
{
    public partial class AddDeviceLedger : DevExpress.XtraEditors.XtraForm
    {
        private string Id;
        public class DeviceTypeDto
        {
            public string Id { get; set; }
            public string Name { get; set; }
        }
        private DeviceLedger data {  get; set; }
        public AddDeviceLedger(string Id)
        {
            InitializeComponent();
            this.CenterToParent();
            this.Id = Id;

        }
        public AddDeviceLedger()
        {
            InitializeComponent();
            this.CenterToParent();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private async void AddDeviceLedger_Load(object sender, EventArgs e)
        {
            // 加载设备类型下拉框
            var a = new List<DeviceTypeDto>()
            {
                new DeviceTypeDto { Id= "1", Name= "CNC机床"  },
                 new DeviceTypeDto { Id= "2", Name= "注塑机"  },
            };
            // 绑定到 ComboBoxEdit1
            lookUpEdit1.Properties.DataSource=a;
            lookUpEdit1.Properties.ValueMember="Id";
            lookUpEdit1.Properties.DisplayMember = "Name";
            lookUpEdit1.Properties.NullText = "请选择";
            lookUpEdit1.Properties.Columns.Clear();
            lookUpEdit1.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "名称"));



            comboBoxEdit1.Properties.Items.AddRange(new List<string>{"小明","小美","小花"});
            comboBoxEdit2.Properties.Items.AddRange(new List<string> { "生产车间", "发货车间", "加工车间" });
            comboBoxEdit3.Properties.Items.AddRange(new List<string> { "董事会", "财务部", "质检部" });
            checkedComboBoxEdit5.Properties.Items.Add( "小花" );
            checkedComboBoxEdit5.Properties.Items.Add("小绿");
            checkedComboBoxEdit5.Properties.Items.Add("小恒");
            if (Id != null) 
            {
                using (HttpClient client = new HttpClient()) 
                {
                    string url = $"{BaseUrl.Url}DeviceLedger/Get?id={Id}";
                    //替换为自己的传值方式"Get","Post","Put","Delete"
                    var response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    var json = await response.Content.ReadAsStringAsync();
                    //替换为你自己的数据模型
                    var result = JsonConvert.DeserializeObject<ApiResult<DeviceLedger>>(json);
                    data = result.ResultData;
                    this.textEdit1.Text=data.AssetNumber;
                    this.textEdit2.Text=data.Code;
                    this.textEdit3.Text=data.Name;
                    this.lookUpEdit1.EditValue="2";
                    this.textEdit5.Text=data.Brand;
                    this.textEdit4.Text=data.Model;
                    this.textEdit6.Text=data.Specification;
                    this.textEdit7.Text = data.Num.ToString();
                    this.comboBoxEdit1.Text=data.SupplierId;
                    this.comboBoxEdit2.Text = data.WorkShopId;
                    this.dateEdit1.Text=data.DateOfManufacture.ToString();
                    this.dateEdit2.Text=data.EntryDateToTheFactory.ToString();
                    this.textEdit8.Text=data.Location;
                    this.comboBoxEdit3.Text=data.DepartmentId;
                    this.checkedComboBoxEdit5.Text=data.PersonInChargeId;
                    this.richTextBox1.Text=data.Remark;
                }
            }
        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            var data = new DeviceLedger();
            data.State = "正常";
            data.Id = "1";
            data.CreatedTime = DateTime.Now;
            data.CreatedUserName = "1";
            // 反向赋值（控件值 → data对象）
            data.AssetNumber = this.textEdit1.Text;
            data.Code = this.textEdit2.Text;
            data.Name = this.textEdit3.Text;
            data.TypeId = this.lookUpEdit1.EditValue.ToString();
            data.Brand = this.textEdit5.Text;
            data.Model = this.textEdit4.Text;
            data.Specification = this.textEdit6.Text;
            // 数值型特殊处理
            if (int.TryParse(this.textEdit7.Text, out int num))
            {
                data.Num = num;
            }
            data.SupplierId = this.comboBoxEdit1.Text;
            data.WorkShopId = this.comboBoxEdit2.Text;
            // 日期型特殊处理
            if (DateTime.TryParse(this.dateEdit1.Text, out DateTime manufactureDate))
            {
                data.DateOfManufacture = manufactureDate;
            }
            if (DateTime.TryParse(this.dateEdit2.Text, out DateTime entryDate))
            {
                data.EntryDateToTheFactory = entryDate;
            }
            data.Location = this.textEdit8.Text;
            data.DepartmentId = this.comboBoxEdit3.Text;
            data.PersonInChargeId = this.checkedComboBoxEdit5.Text;
            data.Remark = this.richTextBox1.Text;
            
            using (HttpClient client = new HttpClient()) 
            {
                var url = string.Empty;
                if (Id != null)
                {
                    url = $"{BaseUrl.Url}DeviceLedger/Update";
                    var jsonStr = JsonConvert.SerializeObject(data);
                    var content = new StringContent(jsonStr, Encoding.UTF8, "application/json");
                    var response = await client.PutAsync(url,content);
                    response.EnsureSuccessStatusCode();
                    var json = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ApiResult<int>>(json);
                    MessageBox.Show(result.Message);
                    // 保存逻辑...
                    this.DialogResult = DialogResult.OK; // 关闭窗口并返回OK
                    this.Close();
                }
                else
                {
                    url = $"{BaseUrl.Url}DeviceLedger/Add";
                    var jsonStr = JsonConvert.SerializeObject(data);
                    var content = new StringContent(jsonStr, Encoding.UTF8, "application/json");
                    var response = await client.PostAsync(url,content);
                    response.EnsureSuccessStatusCode();
                    var json = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ApiResult<int>>(json);
                    MessageBox.Show(result.Message);
                    // 保存逻辑...
                    this.DialogResult = DialogResult.OK; // 关闭窗口并返回OK
                    this.Close();
                }
            }
        }
    }
}